package com.cedarhd.finance.msg.controller.api;

import com.cedarhd.finance.msg.common.JsonResult;
import com.cedarhd.finance.msg.common.ProcessAPI;
import com.cedarhd.finance.msg.common.enums.CacheConstants;
import com.cedarhd.finance.msg.common.enums.ResultCode;
import com.cedarhd.finance.msg.controller.Routes;
import com.cedarhd.finance.msg.domain.service.SmsService;
import com.cedarhd.finance.msg.dto.TemplateMsgDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * 短信服务
 * @author Evan
 * @date 2018/3/7
 */
@Api(value = "短信功能", description = "短信功能")
@RestController
public class SmsController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SmsService smsService;

    private Logger logger = LoggerFactory.getLogger(SmsController.class);

    @ApiOperation(value = "获取Token", notes = "获取Token", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = Routes.SMS_GET_TOKEN, method = RequestMethod.GET)
    public JsonResult getToken(HttpServletRequest request){
        ProcessAPI api = (result, validate) -> {
            String uuid = RandomStringUtils.randomAlphanumeric(32);
            stringRedisTemplate.opsForValue().set(uuid, "1" , 120 , TimeUnit.SECONDS);
            result.setResult(uuid);
        };
        return api.process(request);
    }

    @ApiOperation(value = "发送短信验证码", notes = "发送短信验证码", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = Routes.SMS_SEND_VERIFICATION_CODE, method = RequestMethod.GET)
    public JsonResult sendVerificationCode(HttpServletRequest request,String mobile, String token, String tempId) {
        ProcessAPI api = (result, validate) -> {
            logger.info("sendVerificationCode params =[mobile={},token={},tempId={}]",mobile,token,tempId);
            validate.cheekNull("mobile",mobile);
            validate.cheekNull("token",token);

            if(!StringUtils.isNumeric(mobile)){
                result.setMsg("手机号格式不正确");
                result.setResultCode(ResultCode.FAILED.getCode());
            }

            boolean hasKey = stringRedisTemplate.hasKey(token);
            if(!hasKey){
                logger.info("没有权限发送短信验证码,mobile = {}",mobile);
                result.setMsg(ResultCode.NO_RIGHT.getMsg());
                result.setResultCode(ResultCode.NO_RIGHT.getCode());
                return;
            }

            if(!smsService.sendVerificationCode(mobile,tempId)){
                result.setMsg(ResultCode.FAILED.getMsg());
                result.setResultCode("发送验证码异常!");
                logger.error("sendVerificationCode error mobile={}",mobile);
            }
            stringRedisTemplate.delete(token);
        };
        return api.process(request);
    }

    @ApiOperation(value = "检验验证码", notes = "检验验证码", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @RequestMapping(value = Routes.SMS_VALIDATE_CODE, method = RequestMethod.GET)
    public JsonResult validateCode(HttpServletRequest request,String mobile, String code) {
        ProcessAPI api = (result, validate) -> {
            logger.info("validateCode params=[mobile={},code={}]",mobile,code);
            validate.cheekNull("mobile",mobile);
            validate.cheekNull("code",code);

            //30秒内不能重复提交
            if(stringRedisTemplate.hasKey(CacheConstants.VALIDATE_CODE.getValue()+mobile+code)){
                result.setMsg("30秒内不能重复提交");
                result.setResultCode(ResultCode.FAILED.getCode());
                return;
            }else {
                stringRedisTemplate.opsForValue().set(CacheConstants.VALIDATE_CODE.getValue()+mobile+code, "1", 30, TimeUnit.SECONDS);
            }

            Boolean validateResult = smsService.validateCode(mobile,code);
            if(!validateResult){
                result.setMsg(ResultCode.FAILED.getMsg());
                result.setResultCode(ResultCode.FAILED.getCode());
            }

        };
        return api.process(request);
    }


    /**
     * 发送模版短信
     * @param request
     * @param req
     * @return
     */
    @RequestMapping(value = Routes.SMS_SEND_TEMPLATE_MSG,method = RequestMethod.POST)
    @ApiOperation(value = "发送模版短信", notes = "发送模版短信", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public JsonResult sendTemplateMsg(HttpServletRequest request,@RequestBody TemplateMsgDTO req){
        ProcessAPI api = (result, validate) -> {
            logger.info("sendTemplateMsg params = {}",req.toString());
            validate.cheekNull("mobile",req.getMobile());

            //1分钟内不能重复提交
            if(stringRedisTemplate.hasKey(CacheConstants.TEMPLATE_MSG.getValue()+req.getMobile())){
                result.setMsg("1分钟内不能重复提交");
                result.setResultCode(ResultCode.FAILED.getCode());
                return;
            }else {
                stringRedisTemplate.opsForValue().set(CacheConstants.TEMPLATE_MSG.getValue()+req.getMobile(), "1", 60, TimeUnit.SECONDS);
            }

            Boolean sendResult = smsService.sendTemplateMsg(req);
            if(!sendResult){
                result.setMsg(ResultCode.FAILED.getMsg());
                result.setResultCode(ResultCode.FAILED.getCode());
            }
        };
        return api.process(request);

    }

}
